<template>
  <div class="home">
    <SideBar ref="sidebarRef" @select-character="handleSelectCharacter" @select-conversation="handleSelectConversation"
      @create-new-chat="handleCreateNewChat" @show-role-square="handleShowRoleSquare"
      @show-role-manage="handleShowRoleManage" @conversation-deleted="handleConversationDeleted" />

    <!-- 动态内容区域 -->
    <div class="main-content">
      <!-- 角色广场视图 -->
      <RoleSquare v-if="currentView === 'roleSquare'" @role-selected="handleRoleSelectedFromSquare" />

      <!-- 个人角色管理视图 -->
      <RolePresetManage v-else-if="currentView === 'roleManage'" />

      <!-- 对话视图 -->
      <ChatContainer v-if="currentView === 'chat'" :selected-character="selectedCharacter" :chat-messages="chatMessages"
        :loading="loading" :current-conversation-id="currentConversationId" @send-message="handleSendMessage"
        @add-message="handleAddMessage" @update-message="handleUpdateMessage" @remove-message="handleRemoveMessage"
        @conversation-updated="handleConversationUpdated" @role-selected="handleRoleSelected"
        @show-role-square="currentView = 'roleSquare'" />
    </div>
  </div>
</template>

<script setup>
import SideBar from '@/components/SideBar.vue'
import ChatContainer from '@/components/ChatContainer.vue'
import RoleSquare from '@/views/RoleSquare.vue'
import RolePresetManage from '@/views/RolePresetManage.vue'
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { getMessagesByConversationId, getUserConversations } from '@/api/user.js'
import { ElMessage } from 'element-plus'
import { getRolePresetById } from '@/api/rolePreset.js'
import { streamChat, handleStreamResponse } from '@/api/chat.js'
import { useRoleStore } from '@/stores/role.js'
import router from "@/router/index.js";

// 路由信息
const route = useRoute()

// 角色状态管理
const roleStore = useRoleStore()

// 当前视图状态：'chat' | 'roleSquare' | 'roleManage'
const currentView = ref('chat')

// 当前选中的角色
const selectedCharacter = ref(null)

// 当前会话ID
const currentConversationId = ref(null)

// 聊天记录
const chatMessages = ref([])

// 加载状态
const loading = ref(false)

// 侧边栏引用
const sidebarRef = ref(null)

// 显示角色广场
const handleShowRoleSquare = () => {
  currentView.value = 'roleSquare'
}

// 显示个人角色管理
const handleShowRoleManage = () => {
  currentView.value = 'roleManage'
}

// 处理会话删除事件
const handleConversationDeleted = (deletedConversationId) => {
  // 如果删除的是当前会话，清空聊天内容
  if (currentConversationId.value === deletedConversationId) {
    chatMessages.value = []
    currentConversationId.value = null
    selectedCharacter.value = null
    // 保持在聊天视图但清空内容
  }
}

// 从角色广场选择角色
const handleRoleSelectedFromSquare = (role) => {
  // 设置选中的角色
  selectedCharacter.value = {
    id: role.id,
    name: role.roleName,
    description: role.roleDescription,
    systemPrompt: role.systemPrompt,
    avatarUrl: role.avatarUrl
  }

  // 清空聊天记录，开始新对话
  chatMessages.value = []
  currentConversationId.value = null

  // 切换回对话视图
  currentView.value = 'chat'

  ElMessage.success(`已选择角色：${role.roleName}`)
}

// 选择角色
const handleSelectCharacter = (character) => {
  // 确保character对象格式一致
  selectedCharacter.value = {
    id: character.id,
    name: character.roleName || character.name,
    description: character.roleDescription,
    systemPrompt: character.systemPrompt,
    avatarUrl: character.avatarUrl
  }
  chatMessages.value = []
  currentConversationId.value = null
  currentView.value = 'chat'
}

// 处理角色选择事件
const handleRoleSelected = async (roleId) => {
  if (!roleId) {
    selectedCharacter.value = null
    return
  }

  try {
    const res = await getRolePresetById(roleId)
    if (res && res.code === 200 && res.data) {
      selectedCharacter.value = {
        id: res.data.id,
        name: res.data.roleName,
        description: res.data.roleDescription,
        systemPrompt: res.data.systemPrompt,
        avatarUrl: res.data.avatarUrl
      }
      // 如果是新对话，清空聊天记录
      if (!currentConversationId.value) {
        chatMessages.value = []
      }
      currentView.value = 'chat'
    }
  } catch (error) {
    console.error('获取角色信息失败:', error)
    ElMessage.error('获取角色信息失败')
  }
}

// 监听角色状态变化，替代路由参数监听
watch(() => roleStore.selectedRole, (newRole) => {
  if (newRole && roleStore.isRoleSelected) {
    selectedCharacter.value = newRole
    chatMessages.value = []
    currentConversationId.value = null
    currentView.value = 'chat'
    // 清除状态，避免重复触发
    roleStore.clearSelectedRole()
  }
})

// 监听路由变化，处理不同页面的显示
watch(() => route.name, (newRouteName) => {
  if (newRouteName === 'roleSquare') {
    currentView.value = 'roleSquare'
  } else if (newRouteName === 'home') {
    currentView.value = 'chat'
  }
}, { immediate: true })

// 组件挂载时，检查是否有待处理的角色选择
onMounted(() => {
  // 根据路由名称设置初始视图
  if (route.name === 'roleSquare') {
    currentView.value = 'roleSquare'
  } else if (route.name === 'home') {
    currentView.value = 'chat'
  }

  if (roleStore.selectedRole && roleStore.isRoleSelected) {
    selectedCharacter.value = roleStore.selectedRole
    chatMessages.value = []
    currentConversationId.value = null
    currentView.value = 'chat'
    roleStore.clearSelectedRole()
  }
})

// 加载历史对话消息
const loadConversationMessages = async (conversationId) => {
  if (!conversationId) return
  
  // 防止重复加载消息
  if (isLoadingMessages.value) {
    console.log('正在加载消息，跳过重复请求')
    return
  }
  
  isLoadingMessages.value = true
  loading.value = true
  currentConversationId.value = conversationId

  try {
    const res = await getMessagesByConversationId(conversationId)
    console.log('API返回数据:', res)

    if (res && Array.isArray(res)) {
      chatMessages.value = res.map(msg => {
        return {
          id: msg.timestamp || Date.now(),
          type: msg.type === 'USER' ? 'user' : 'ai',
          content: msg.content || ''
        }
      })

      setTimeout(() => {
        const messageContainer = document.querySelector('.chat-messages')
        if (messageContainer) {
          messageContainer.scrollTop = messageContainer.scrollHeight
        }
      }, 100)
    } else if (res && res.data && Array.isArray(res.data)) {
      chatMessages.value = res.data.map(msg => {
        return {
          id: msg.timestamp || Date.now(),
          type: msg.type === 'USER' ? 'user' : 'ai',
          content: msg.content || ''
        }
      })

      setTimeout(() => {
        const messageContainer = document.querySelector('.chat-messages')
        if (messageContainer) {
          messageContainer.scrollTop = messageContainer.scrollHeight
        }
      }, 100)
    } else {
      console.error('API返回数据格式不正确:', res)
      ElMessage.warning('获取对话消息失败')
    }
  } catch (error) {
    console.error('获取对话消息失败:', error)
    ElMessage.error('获取对话消息失败')
  } finally {
    loading.value = false
    isLoadingMessages.value = false
  }
}

// 处理会话选择
const handleSelectConversation = (conversation) => {
  selectedCharacter.value = {
    id: conversation.roleId,
    name: conversation.title
  }
  loadConversationMessages(conversation.id)
  currentView.value = 'chat'
}

// 防止重复加载的标志
const isLoadingConversation = ref(false)
// 防止重复加载消息的标志
const isLoadingMessages = ref(false)

// 从路由加载会话
const loadConversationFromRoute = async (conversationId) => {
  // 防止重复加载
  if (isLoadingConversation.value) {
    console.log('正在加载会话，跳过重复请求')
    return
  }
  
  // 如果当前会话ID和要加载的会话ID相同，跳过
  if (currentConversationId.value === conversationId) {
    console.log('会话ID相同，跳过重复加载')
    return
  }
  
  isLoadingConversation.value = true
  
  try {
    // 等待SideBar加载完成
    let retryCount = 0
    while (retryCount < 20) { // 最多等待2秒
      if (sidebarRef.value && sidebarRef.value.isConversationsLoaded) {
        break
      }
      await new Promise(resolve => setTimeout(resolve, 100))
      retryCount++
    }
    
    // 从SideBar获取会话列表
    const conversationList = sidebarRef.value?.conversationList || []
    const conversation = conversationList.find(conv => conv.id === conversationId)
    
    if (conversation) {
      // 设置选中的角色
      selectedCharacter.value = {
        id: conversation.roleId,
        name: conversation.title
      }
      // 加载会话消息
      await loadConversationMessages(conversationId)
      // 切换到聊天视图
      currentView.value = 'chat'
      console.log('成功加载会话:', conversation)
    } else {
      console.warn('未找到对应的会话:', conversationId)
      ElMessage.warning('会话不存在或已被删除')
    }
  } catch (error) {
    console.error('从路由加载会话失败:', error)
    ElMessage.error('加载会话失败')
  } finally {
    isLoadingConversation.value = false
  }
}

// 记录上次加载的会话ID，避免重复加载
const lastLoadedConversationId = ref(null)

// 监听路由参数变化
watch(() => route.params.id, (conversationId) => {
  console.log('路由参数变化，会话ID:', conversationId)
  if (conversationId && conversationId !== lastLoadedConversationId.value) {
    lastLoadedConversationId.value = conversationId
    loadConversationFromRoute(conversationId)
  }
}, { immediate: true })

// 发送消息
// 添加组件销毁标志
const isDestroyed = ref(false)

// 在组件销毁时设置标志
onUnmounted(() => {
  isDestroyed.value = true
})

// 修改handleSendMessage方法中的DOM操作
const handleSendMessage = async (message) => {
  // 确保已选择角色
  if (!selectedCharacter.value) {
    ElMessage.warning('请先选择一个角色')
    return
  }

  // 添加用户消息到聊天记录
  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: message
  }
  chatMessages.value.push(userMessage)

  // 添加AI消息占位符
  const aiMessageId = Date.now() + 1
  const aiMessage = {
    id: aiMessageId,
    type: 'ai',
    content: ''
  }
  chatMessages.value.push(aiMessage)

  // 确保消息滚动到底部（添加销毁检查）
  setTimeout(() => {
    if (!isDestroyed.value) {
      const messageContainer = document.querySelector('.chat-messages')
      if (messageContainer) {
        messageContainer.scrollTop = messageContainer.scrollHeight
      }
    }
  }, 100)

  // 设置加载状态
  loading.value = true

  try {
    // 准备请求参数
    const params = {
      memoryId: currentConversationId.value || Date.now().toString(),
      roleId: selectedCharacter.value.id,
      message: message
    }

    // 如果是新对话，更新currentConversationId
    if (!currentConversationId.value) {
      currentConversationId.value = params.memoryId
    }

    // 发送流式请求
    const response = await streamChat(params)

    // 处理流式响应
    let fullResponse = ''
    await handleStreamResponse(
      response,
      (chunk) => {
        // 更新AI消息内容
        fullResponse += chunk
        const aiMessageIndex = chatMessages.value.findIndex(msg => msg.id === aiMessageId)
        if (aiMessageIndex !== -1) {
          chatMessages.value[aiMessageIndex].content = fullResponse
        }

        // 确保消息滚动到底部（添加销毁检查）
        if (!isDestroyed.value) {
          const messageContainer = document.querySelector('.chat-messages')
          if (messageContainer) {
            messageContainer.scrollTop = messageContainer.scrollHeight
          }
        }
      },
      async () => {
        // 响应完成
        loading.value = false

        // 更新历史对话列表
        const updateConversationList = async () => {
          try {
            // 直接调用SideBar组件的fetchConversations方法
            if (sidebarRef.value && typeof sidebarRef.value.fetchConversations === 'function') {
              await sidebarRef.value.fetchConversations()
            }
          } catch (error) {
            console.error('更新会话列表失败:', error)
          }
        }
        await updateConversationList()
      }
    )
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
    loading.value = false

    // 移除AI消息占位符
    chatMessages.value = chatMessages.value.filter(msg => msg.id !== aiMessageId)
  }
}

// 处理创建新对话
const handleCreateNewChat = () => {
  // 清空当前会话ID
  currentConversationId.value = null

  // 清空选中的角色
  selectedCharacter.value = null

  // 清空聊天记录
  chatMessages.value = []

  // 重置加载状态
  loading.value = false

  // 切换到对话视图
  currentView.value = 'chat'
}

// 添加消息到聊天记录
const handleAddMessage = (message) => {
  chatMessages.value.push(message)
}

// 更新消息内容
const handleUpdateMessage = (updatedMessage) => {
  const index = chatMessages.value.findIndex(msg => msg.id === updatedMessage.id)
  if (index !== -1) {
    chatMessages.value[index] = { ...updatedMessage }
  }
}

// 移除消息
const handleRemoveMessage = (messageId) => {
  const index = chatMessages.value.findIndex(msg => msg.id === messageId)
  if (index !== -1) {
    chatMessages.value.splice(index, 1)
  }
}

// 会话更新处理
const handleConversationUpdated = async (data) => {
  // 更新当前会话ID
  if (data.conversationId) {
    currentConversationId.value = data.conversationId
  }

  // 刷新会话列表
  try {
    if (sidebarRef.value && typeof sidebarRef.value.fetchConversations === 'function') {
      await sidebarRef.value.fetchConversations()
    }
  } catch (error) {
    console.error('刷新会话列表失败:', error)
  }

  // 如果提供了角色信息，更新选中的角色
  if (data.roleId && data.roleName) {
    selectedCharacter.value = {
      id: data.roleId,
      name: data.roleName,
      description: data.roleDescription || '',
      systemPrompt: data.systemPrompt || '',
      avatarUrl: data.avatarUrl || ''
    }
  }

  // 如果需要加载该会话的消息历史
  if (data.loadMessages && data.conversationId) {
    await loadConversationMessages(data.conversationId)
  }
}
</script>

<style scoped>
.home {
  display: flex;
  height: 100vh;
  width: 100%;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  /* 移除 overflow-y: auto; 让子组件自己处理滚动 */
  min-height: 0; /* 确保flex子元素可以收缩 */
}
</style>
